package controllers
{
	import com.greensock.events.LoaderEvent;
	import com.greensock.loading.DataLoader;
	import com.greensock.loading.ImageLoader;
	import com.greensock.loading.LoaderMax;
	import com.greensock.loading.MP3Loader;
	import com.pamakids.manager.LoadManager;
	import com.pamakids.utils.CloneUtil;

	import flash.display.BitmapData;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.media.Sound;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;

	import models.PaintData;
	import models.PaintVO;
	import models.VO;
	import models.quiz.ChoiceQuizVO;
	import models.quiz.FindQuizVO;
	import models.quiz.JigsawQuizVO;
	import models.quiz.OptionVO;
	import models.quiz.QuickspotQuizVO;
	import models.quiz.QuizData;
	import models.quiz.QuizUtils;
	import models.quiz.QuizVO;
	import models.quiz.RecordQuizVO;
	import models.quiz.SortBlockVO;
	import models.quiz.SortQuizVO;
	import models.quiz.StemVO;

	import views.anime.AnimeData;
	import views.anime.MCSequence;

	public class PaintLoader extends EventDispatcher
	{
		private var paint:PaintVO;
		private var _queue:LoaderMax;
		public function PaintLoader(_paint:PaintVO)
		{
			paint=_paint;
		}

		public function get audio():String
		{
			return paint.audio;
		}

		public function init():void
		{
			if(_queue)
				return;
			_queue = new LoaderMax({name:"childQueue",onComplete:completeHandler,onError:errorHandler,
					onProgress:progressFunction,maxConnections:3});

			if(paint.data&&paint.data.indexOf(VO.DATA_NAME)<0&&paint.data.indexOf(VO.VIDEO_NAME_FLV)<0)
				LoadManager.instance.loadText(paint.dataUrl,onLoadDataComplete,'',onIO);
			else
			{
				coverUrl = paint.cover;
				_queue.append(new ImageLoader(VO.FILESERVER_HOST+coverUrl,{name:coverUrl}));
				if(paint.audio)
				{
					sndUrl=paint.audio;
					if(sndUrl.indexOf(VO.AUDIO_NAME_AMR)>0)
						sndUrl+=VO.AUDIO_MP3;
					bgSnd = new Sound(new URLRequest(VO.FILESERVER_HOST+sndUrl));
//                    _queue.append(new MP3Loader(VO.FILESERVER_HOST+sndUrl,{name:sndUrl,autoPlay:false}));
				}

				_queue.load();
			}
		}

		private var bgSnd:Sound;

		private function errorHandler(event:LoaderEvent):void
		{
			dispatchEvent(new ErrorEvent(ErrorEvent.ERROR,false,false,event.text));
		}

		public var paintData:PaintData;

		private function onLoadDataComplete(s:String):void
		{
			if(s.indexOf('replayData')>=0)
				onLoadAnimeDataComplete(s);
			else if(s.indexOf('quizArr')>=0)
				onLoadQuizDataComplete(s);
			else
				dispatchEvent(new Event(Event.COMPLETE));
		}

		private function onIO(o:*,p:*):void
		{
			trace(o);
		}

		private function onLoadQuizDataComplete(s:String):void
		{
			s=s.substr(s.indexOf("{"));
			quizData = new QuizData();
			var quizObj:Object = JSON.parse(s);
			coverUrl = paint.cover;
			_queue.append(new ImageLoader(VO.FILESERVER_HOST+coverUrl,{name:coverUrl}));

			if(paint.audio)
			{
				sndUrl=paint.audio;
				if(sndUrl.indexOf(VO.AUDIO_NAME_AMR)>0)
					sndUrl+=VO.AUDIO_MP3;
				_queue.append( new MP3Loader(VO.FILESERVER_HOST+sndUrl, {name:sndUrl,autoPlay:false}));
			}

			if(quizObj.quizArr)
			{
				var qarr:Array = QuizUtils.parseQuizs(quizObj.quizArr);
				quizData.quizArr = qarr;

				for (var i:int = 0; i < qarr.length; i++) 
				{
					var obj:QuizVO = qarr[i];
					switch(obj.type)
					{
						case 0:
						{
							var findvo:FindQuizVO = obj as FindQuizVO;

							_queue.append( new MP3Loader(VO.FILESERVER_HOST+findvo.snd, {name:findvo.snd,autoPlay:false}));
							if(findvo.rightSnd)
								_queue.append( new MP3Loader(VO.FILESERVER_HOST+findvo.rightSnd, {name:findvo.rightSnd,autoPlay:false}));
							if(findvo.wrongSnd)
								_queue.append( new MP3Loader(VO.FILESERVER_HOST+findvo.wrongSnd, {name:findvo.wrongSnd,autoPlay:false}));

							_queue.append( new ImageLoader(VO.FILESERVER_HOST+findvo.src, {name:findvo.src}));
							break;
						}

						default:
						{
							break;
						}
					}

				}
			}else if(quizObj.quiz)
			{
				var quiz:QuizVO = QuizUtils.parseQuiz(quizObj.quiz);
				quizData.quiz = quiz;

				var wrongsnds:Array
				var animes:Array;

				switch(quiz.type)
				{
					case 1:
					{
						var choicevo:ChoiceQuizVO = quiz as ChoiceQuizVO;

						var stem:StemVO = choicevo.stem;
						if(stem.snd)
							_queue.append( new MP3Loader(VO.FILESERVER_HOST+stem.snd, {name:stem.snd,autoPlay:false}));
						if(stem.src)
							_queue.append( new ImageLoader(VO.FILESERVER_HOST+stem.src, {name:stem.src}));

						if(choicevo.rightSnd)
							_queue.append( new MP3Loader(VO.FILESERVER_HOST+choicevo.rightSnd, {name:choicevo.rightSnd,autoPlay:false}));

						wrongsnds = choicevo.wrongSndArr;
						for (var j1:int = 0; j1 < wrongsnds.length; j1++) 
						{
							var fb1:String = wrongsnds[j1];
							if(fb1)
								_queue.append( new MP3Loader(VO.FILESERVER_HOST+fb1, {name:fb1,autoPlay:false}));
						}

						var options:Array = choicevo.options;
						for (var k1:int = 0; k1 < options.length; k1++) 
						{
							var option:OptionVO = options[k1];
							if(option.snd)
								_queue.append( new MP3Loader(VO.FILESERVER_HOST+option.snd, {name:option.snd,autoPlay:false}));
							if(option.src)
								_queue.append( new ImageLoader(VO.FILESERVER_HOST+option.src, {name:option.src}));
						}

						animes = choicevo.animes;
						if(animes&&animes.length)
							loadAnimes(_queue,animes);

						break;
					}

					case 2:
					{
						var sortvo:SortQuizVO = quiz as SortQuizVO;

						if(sortvo.rightSnd)
							_queue.append( new MP3Loader(VO.FILESERVER_HOST+sortvo.rightSnd, {name:sortvo.rightSnd,autoPlay:false}));

						if(sortvo.wrongSnd)
							_queue.append( new MP3Loader(VO.FILESERVER_HOST+sortvo.wrongSnd, {name:sortvo.wrongSnd,autoPlay:false}));

						wrongsnds = sortvo.wrongSndArr;
						for (var j2:int = 0; j2 < wrongsnds.length; j2++) 
						{
							var fb2:String = wrongsnds[j2];
							if(fb2)
								_queue.append( new MP3Loader(VO.FILESERVER_HOST+fb2, {name:fb2,autoPlay:false}));
						}

						var sorts:Array = sortvo.sorts;
						for (var k2:int = 0; k2 < sorts.length; k2++) 
						{
							var sort:SortBlockVO = sorts[k2];
							if(sort.snd)
								_queue.append( new MP3Loader(VO.FILESERVER_HOST+sort.snd, {name:sort.snd,autoPlay:false}));
							if(sort.src)
								_queue.append( new ImageLoader(VO.FILESERVER_HOST+sort.src, {name:sort.src}));
						}

						animes = sortvo.animes;
						if(animes&&animes.length)
							loadAnimes(_queue,animes);

						break;
					}

					case 3:
					{
						var quickvo:QuickspotQuizVO = quiz as QuickspotQuizVO;

						if(quickvo.rightSnd)
							_queue.append( new MP3Loader(VO.FILESERVER_HOST+quickvo.rightSnd, {name:quickvo.rightSnd,autoPlay:false}));

						if(quickvo.wrongSnd)
							_queue.append( new MP3Loader(VO.FILESERVER_HOST+quickvo.wrongSnd, {name:quickvo.wrongSnd,autoPlay:false}));

						wrongsnds = quickvo.wrongSndArr;
						for (var j3:int = 0; j3 < wrongsnds.length; j3++) 
						{
							var fb3:String = wrongsnds[j3];
							if(fb3)
								_queue.append( new MP3Loader(VO.FILESERVER_HOST+fb3, {name:fb3,autoPlay:false}));
						}

						break;
					}

					case 4:
					{
						var jigsawvo:JigsawQuizVO = quiz as JigsawQuizVO;

						if(jigsawvo.rightSnd)
							_queue.append( new MP3Loader(VO.FILESERVER_HOST+jigsawvo.rightSnd, {name:jigsawvo.rightSnd,autoPlay:false}));

						if(jigsawvo.wrongSnd)
							_queue.append( new MP3Loader(VO.FILESERVER_HOST+jigsawvo.wrongSnd, {name:jigsawvo.wrongSnd,autoPlay:false}));

						wrongsnds = jigsawvo.wrongSndArr;
						if(wrongsnds)
							for (var j4:int = 0; j4 < wrongsnds.length; j4++) 
							{
								var fb4:String = wrongsnds[j4];
								if(fb4)
									_queue.append( new MP3Loader(VO.FILESERVER_HOST+fb4, {name:fb4,autoPlay:false}));
							}

						break;
					}

					case 5:
					{
						var recordquizvo:RecordQuizVO = quiz as RecordQuizVO;

						if(recordquizvo.rightSnd)
							_queue.append( new MP3Loader(VO.FILESERVER_HOST+recordquizvo.rightSnd, {name:recordquizvo.rightSnd,autoPlay:false}));

						if(recordquizvo.wrongSnd)
							_queue.append( new MP3Loader(VO.FILESERVER_HOST+recordquizvo.wrongSnd, {name:recordquizvo.wrongSnd,autoPlay:false}));

						wrongsnds = recordquizvo.wrongSndArr;
						if(wrongsnds)
							for (var j5:int = 0; j5 < wrongsnds.length; j5++) 
							{
								var fb5:String = wrongsnds[j5];
								if(fb5)
									_queue.append( new MP3Loader(VO.FILESERVER_HOST+fb5, {name:fb5,autoPlay:false}));
							}

						animes = recordquizvo.animes;
						if(animes&&animes.length)
							loadAnimes(_queue,animes);

						break;
					}

					default:
					{
						break;
					}
				}
			}
			_queue.load();
		}

		private function loadAnimes(_queue:LoaderMax, animes:Array):void
		{
			for (var i:int = 0; i < animes.length; i++) 
			{
				var anime:Object = animes[i];
				var key:String = anime.key;
				var arr:Array = key.split(MCSequence.DIV);
				if(arr.length==2)//加载动画序列
				{
					var key1:String = arr[0];
					_queue.append( new DataLoader(VO.FILESERVER_HOST+key1, {name:key1}));
					var tkey1:String = key1.replace(".json",".png");
					_queue.append( new ImageLoader(VO.FILESERVER_HOST+tkey1, {name:tkey1}));

					var key2:String = arr[1];
					_queue.append( new DataLoader(VO.FILESERVER_HOST+key2, {name:key2}));
					var tkey2:String = key2.replace(".json",".png");
					_queue.append( new ImageLoader(VO.FILESERVER_HOST+tkey2, {name:tkey2}));
				}
				else if(key.indexOf(".json")>=0)//加载动态贴纸
				{
					_queue.append( new DataLoader(VO.FILESERVER_HOST+key, {name:key}));
					var tkey:String = key.replace(".json",".png");
					_queue.append( new ImageLoader(VO.FILESERVER_HOST+tkey, {name:tkey}));
				}else
					_queue.append( new ImageLoader(VO.FILESERVER_HOST+key, {name:key}));
			}
		}

		private function loadSnd(url:String):void
		{
			if(!url)
				return;
			if(sndDic[url])
				return;
			var snd:Sound;
			if(url.indexOf(VO.AUDIO_NAME_AMR)>0)
				snd = new Sound(new URLRequest(VO.FILESERVER_HOST+url+VO.AUDIO_MP3));
			else 
				snd = new Sound(new URLRequest(VO.FILESERVER_HOST+url));
			snd.addEventListener(IOErrorEvent.IO_ERROR,onSndError);
			sndDic[url] = snd;
		}

		protected function onSndError(event:IOErrorEvent):void
		{

		}

		private function onLoadAnimeDataComplete(s:String):void
		{
			s=s.substr(s.indexOf("{"));
			animeData=CloneUtil.convertObject(JSON.parse(s),AnimeData);
			var tarr:Array=animeData.textures;
			for (var i:int = 0; i < tarr.length; i++) 
			{
				var key:String = tarr[i];
				if(key.indexOf(".json")>=0)//加载动态贴纸
				{
					_queue.append( new DataLoader(VO.FILESERVER_HOST+key, {name:key}));
					var tkey:String = key.replace(".json",".png");
					_queue.append( new ImageLoader(VO.FILESERVER_HOST+tkey, {name:tkey}));
				}else
					_queue.append( new ImageLoader(VO.FILESERVER_HOST+key, {name:key}));
			}

			coverUrl=animeData.background;
			_queue.append(new ImageLoader(VO.FILESERVER_HOST+coverUrl,{name:coverUrl}));

			if(paint.audio)
			{
				sndUrl=paint.audio;
				if(sndUrl.indexOf(VO.AUDIO_NAME_AMR)>0)
					sndUrl+=VO.AUDIO_MP3;
				bgSnd = new Sound(new URLRequest(VO.FILESERVER_HOST+sndUrl));
//                _queue.append(new MP3Loader(VO.FILESERVER_HOST+sndUrl,{name:sndUrl,autoPlay:false}));
			}

			_queue.load();
		}

		public function dispose():void
		{
			for each (var s:Sound in sndDic) 
			{
//				delete sndDic[s];
				try
				{
					s.close();
					s=null;
				} 
				catch(error:Error) 
				{
				}
			}

			if(_queue)
				_queue.dispose(true);
			_queue=null;
		}

		public var animeData:AnimeData;
		public var quizData:QuizData;

		private var sndUrl:String;
		private var coverUrl:String;

		private function completeHandler(event:LoaderEvent):void 
		{
			dispatchEvent(new Event(Event.COMPLETE));
		}

		private function progressFunction(event:LoaderEvent):void 
		{
//            dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS,false,false,
			_queue.progress;
		}

		public function getBitmapByName(name:String):BitmapData
		{
			var obj:Object=_queue.getContent(name);
			if(obj&&obj.rawContent)
				return obj.rawContent.bitmapData.clone();
			return null;
		}

		public function getBG():BitmapData
		{
			return getBitmapByName(coverUrl);
		}

		public function getMP3():Sound
		{
			return bgSnd;
//            if(sndUrl)
//                return _queue.getContent(sndUrl);
//            return null;
		}

		private var sndDic:Dictionary = new Dictionary;

		public function getSnd(snd:String):Sound
		{
			if(snd)
				return _queue.getContent(snd);
//                return sndDic[snd];
			return null;
		}

		public function getConfig(key:String):Object
		{
			if(key)
			{
				var s:String =  _queue.getContent(key);
				if(s)
					return JSON.parse(s);
			}
			return null;
		}

		public var ready:Boolean
	}
}

